/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author         Notes
 * 2019-07-28     Ernest         the first version
 */

 #include "board.h"
 #include <rtthread.h>
 #include <rtdevice.h>

 
#define DBG_TAG              "drv.sound"
#define DBG_LVL              DBG_INFO
#include <rtdbg.h>

rt_mailbox_t dac_mbox;
 
 /****************************************************************************
 * @brief 录音线程, 与usb交互
 ****************************************************************************/
#include "usbd_core.h"
static void play_thread_entry(void *parameter)
{

  #define AUDIO_OUT_PACKET 192 /*192字节, 48k采样率, 2声道, 16位 */
  #define AUDIO_OUT_EP 0x02
  extern uint8_t read_buffer[AUDIO_OUT_PACKET];
  int16_t *pdata =rt_malloc(AUDIO_OUT_PACKET);

  rt_device_t sound_dev;
  rt_ubase_t written;
  
  sound_dev = rt_device_find("dao");
  RT_ASSERT(rt_device_open(sound_dev, RT_DEVICE_OFLAG_WRONLY) == RT_EOK);


  struct rt_audio_caps caps;
  /* set sampletate,channels, samplebits */
  caps.main_type = AUDIO_TYPE_OUTPUT;
  caps.sub_type  = AUDIO_DSP_SAMPLERATE;
  caps.udata.config.samplerate = 24000; /*48kHz/2=24kHz, 只有这样设置，声音才正常*/
  rt_device_control(sound_dev, AUDIO_CTL_CONFIGURE, &caps);

  while(1){
    if (rt_mb_recv(dac_mbox, &written, RT_WAITING_FOREVER) == RT_EOK)
    { 
      written = rt_device_write(sound_dev, 0, read_buffer, written);
      usbd_ep_start_read(0, AUDIO_OUT_EP, read_buffer, AUDIO_OUT_PACKET);
    }
  }
}

static int play_thread()
{
  dac_mbox = rt_mb_create("dac_mbox", 100, RT_IPC_FLAG_FIFO);

  extern void audio_v1_init(uint8_t busid, uintptr_t reg_base);
  board_init_usb_pins();
  audio_v1_init(0, HPM_USB0_BASE);

    rt_thread_t thread;
    thread = rt_thread_create("play_thread", play_thread_entry, RT_NULL, 2048, 2, 10);
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
    return 0;
}
INIT_APP_EXPORT(play_thread);
 